from django.shortcuts import render, redirect
from django.http import HttpResponse  # 返回请求必须的类

from BookApp.models import BookCharacter, BookInfo

from datetime import datetime, date


# Create your views here.


def test(request):
    """联通性测试"""
    return HttpResponse("========== ok ==========")
    pass


def bookList(req):
    """图书列表"""

    # 从mysql数据库读取所有图书列表
    allBooks = BookInfo.objects.all()

    return HttpResponse(render(req, "BookAppTemplates/blist.html", {"booklist": allBooks}))
    pass


def addBook(req):
    """新增图书-重定向到blist.html页面"""

    # 添加数据
    b = BookInfo()
    b.title = "葫芦娃传说"
    b.auhtor = "老爷爷"
    b.year = datetime(1980, 11, 9)
    b.save()

    return redirect('/app/api/BookApp/booklist')  # 让页面重定向到 blist.html 页面
    pass


def deleteBook(req, bid):
    """删除添加的图书"""

    # 删除id指向的书籍
    b = BookInfo.objects.get(id=bid)
    b.delete()
    return redirect('/app/api/BookApp/booklist')  # 让页面重定向到 blist.html 页面
    pass


def bookDetail(req, bid):
    """查看图书中人物"""

    character =  BookCharacter.objects.filter(foreignKey__id=bid)
    return HttpResponse(render(req, "BookAppTemplates/bdetail.html", {"bookCharacter": character}))
    pass

